//
// Created by 董一龙 on 2022/10/15.
//
#include "mmaplib/platform/mac/macos_adaptation.h"
#include <sys/mman.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include <filesystem>
#include <sys/stat.h>

namespace fqueue {
    void *
    macos_adaptation::mmap(void *addr, size_t length, int prot, int flags, const char *const filename, off_t offset) {
        int fd = open(filename, O_RDWR);
        void *result = ::mmap(addr, length, prot, flags, fd, offset);
        close(fd);
        return result;
    }

    int macos_adaptation::munmap(void *addr, size_t length) {
        ::munmap(addr, length);
        return 0;
    }

    int macos_adaptation::create_file(const char *filename, size_t file_size) {
        int fd = creat(filename, S_IRUSR | S_IWUSR);
        if (fd == -1) {
            errno;
        }
        close(fd);
        chmod(filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
        truncate(filename, file_size);
        assert(file_size == std::filesystem::file_size(filename));
        return 0;
    }

    size_t macos_adaptation::file_size(const char *filename) {
        return std::filesystem::file_size({filename});
    }

    bool macos_adaptation::exists(char const*const filename) {
        return access(filename, 2 | 4);
    }
} // fqueue